package com.direct.ssh.service.impl;

import java.util.Date;

import com.direct.ssh.common.DateUtils;
import com.direct.ssh.dao.CustomerDao;
import com.direct.ssh.domain.Customer;
import com.direct.ssh.exception.LoginException;
import com.direct.ssh.service.LoginService;

public class LoginServiceImpl implements LoginService {

	private CustomerDao customerDao;
	
	public Customer login(Customer customer) throws LoginException {
		
		Customer dbcustomer = null;
		
		try {
			//根据用户名查找账户信息
			dbcustomer = customerDao.querySingle("from t_customer c where c.username = ?", 
					new Object[] {customer.getUsername()});
			
		} catch(RuntimeException e) {
			e.printStackTrace();
			throw new LoginException("数据库连接失败", e);
		}
		//账户不存在
		if(dbcustomer == null) {
			throw new LoginException("账号不存在");
		}
		//如果上次登录是今天之前,清除错误次数
		if(dbcustomer.getLastLoginTime().getTime() < DateUtils.getToday().getTime()) {
			dbcustomer.setPasswordErrorCount(0);
		}
		//修改登录时间为当前时间
		dbcustomer.setLastLoginTime(new Date());
		//如果密码错误次数大于三次
		if(dbcustomer.getPasswordErrorCount() >= 3) {
			throw new LoginException("今天的错误次数已达上限,请明天再试!");
		}
		//密码错误
		if(! dbcustomer.getPassword().equals(customer.getPassword())) {
			
			dbcustomer.setPasswordErrorCount(dbcustomer.getPasswordErrorCount() + 1);
			
			throw new LoginException("密码错误!");
		}
		
		return dbcustomer;
	}

	public CustomerDao getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

}
